# coding: utf-8
import json
from datetime import datetime
from flask import Blueprint, render_template, request
from leancloud import Query, LeanCloudError
from tools import logging, wrapsfuncs
from dbModels import AgmSeller, Cache_dict, WepaySuccess
from wechatpay import WEPAYORDERID
from agmbeta import printDateTime

app = Blueprint('agmpay', __name__)

@app.route('/', methods=['GET', 'POST'])
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission('agmadmin')
def index():
    if request.method == 'POST':
        pid = request.args.get('pid')
        order = Query(Cache_dict).get(WEPAYORDERID)
        orderdict = order.get('content')
        attrs = ['total_fee', 'no_subscribe_fee', 'reward']
        if pid not in orderdict:
            return 'inValidPid'
        try:
            for attr in attrs:
                orderdict[pid][attr] = int(float(request.form.get(attr))*100)
            orderdict[pid]['body'] = request.form.get('body')
            order.set('content', orderdict)
            order.save()
            return 'saveDone'
        except (TypeError, ValueError):
            return 'inValidData'
        reward = request.form.get('reward')
        return 'POST Done! %s, %s' % (pid, reward)
    orderdict = {
        "1001": {
            "total_fee": 2,
            "body": "音速风暴最新赛车体验活动1",
            "attach": "ohCrcvq5TTqoF1eP4p2oLn6rte2k",
            "no_subscribe_fee": 3,
            "reward": 1,
        },
        "1002": {
            "total_fee": 2,
            "body": "音速风暴最新赛车体验活动2",
            "attach": "ohCrcvuJKvV1jRKGv_ZsUg_Z22SA",
            "no_subscribe_fee": 3,
            "reward": 1
        },
        "1003": {
            "total_fee": 3,
            "body": "音速风暴最新赛车体验活动3",
            "attach": "ohCrcvq5TTqoF1eP4p2oLn6rte2k",
            "no_subscribe_fee": 4,
            "reward": 2,
        }        
    }
    orderdict = Query(Cache_dict).get(WEPAYORDERID).get('content')
    sellers = {}
    openids = []
    for t in orderdict:
        openid = orderdict[t].get('attach')
        if openid not in sellers:
            sellers[openid] = {'product_id': [t]}
            openids.append(openid)
        else:
            sellers[openid]['product_id'].append(t)
    getids = Query(AgmSeller).contained_in('openid', openids).find()
    if getids:
        for t in getids:
            openid = t.get('openid')
            sellers[openid]['sid'] = t.id
            sellers[openid]['nickname'] = t.get('nickname')
            sellers[openid]['headimgurl'] = t.get('headimgurl')
            sellers[openid]['shopname'] = t.get('shopname')
            
    return render_template('agm1.0/pay/agm_seller_payset.html', 
        orderdict=orderdict, openids=openids, sellers=sellers, json=json)
        
@app.route('/record')
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission('agmadmin')
def record(): 
    # sellers = Query(AgmSeller).find()
    order = Query(Cache_dict).get(WEPAYORDERID).get('content')
    openids= []
    for t in order:
        if order[t].get('attach') not in openids:
            openids.append(order[t].get('attach'))
    sellers = Query(AgmSeller).contained_in('openid', openids).find()
    for seller in sellers:
        seller.r_count = Query(WepaySuccess).equal_to('attach', seller.get('openid')).not_contained_in ('rewardstat', [1, -1]).count()
    sellers.sort(key=lambda x:x.r_count, reverse=True)    
        
    return render_template('agm1.0/pay/agm_seller_list.html', 
        sellers=sellers)
        
@app.route('/selleraward', methods=['GET', 'POST'])
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission('agmadmin')
def selleraward():
    if request.method == 'POST':
        action = request.args.get('action')
        if action == 'rewardseller':
            orderdict = Query(Cache_dict).get(WEPAYORDERID).get('content')
            rewardids = request.form.get('rewardids').strip('|').split('|')
            rewardsum = 0
            sucids = []
            failids = []
            for rid in rewardids:
                try:
                    sellrecord = Query(WepaySuccess).get(rid)
                    if sellrecord.get('rewardstat') == 0:
                        reward = orderdict.get(sellrecord.get('product_id'), 0) and orderdict[sellrecord.get('product_id')]['reward']
                        sellrecord.set('rewardstat', 1)
                        sellrecord.set('rewardtime', datetime.utcnow())
                        sellrecord.set('reward', reward)
                        sellrecord.save()
                        rewardsum += reward
                        sucids.append([rid, printDateTime(sellrecord.get('rewardtime'), '%Y-%m-%d %H:%M:%S')])
                    else:
                        failids.append(rid)
                except LeanCloudError:
                    failids.append(rid)                    
            return json.dumps({'sucids': sucids, 'failids': failids, 'rewardsum': rewardsum/100.0})
            
    uid = request.args.get('uid')
    if not uid:
        abort(404)
    agmseller = Query(AgmSeller).get(uid)
    openid = agmseller.get('openid')
    records = Query(WepaySuccess).equal_to('attach', openid).descending('createdAt').find()
    orderdict = Query(Cache_dict).get(WEPAYORDERID).get('content')
    rewarded = []
    reward_wait = []
    total = 0
    for r in records:
        r.set('time_end', datetime.strptime(r.get('time_end'), '%Y%m%d%H%M%S'))
        r.set('total_fee', int(r.get('total_fee'))/100.0)
        if not r.get('reward'): #r.get('reward') is None:
            r.set('reward', orderdict.get(r.get('product_id'), 0) and orderdict[r.get('product_id')]['reward']/100.0)
        else:
            r.set('reward', r.get('reward')/100.0)
        if r.get('rewardstat') == 0:
            reward_wait.append(r)
            total += r.get('reward')
        elif r.get('rewardstat') == -1:
            reward_wait.append(r)
        else:
            rewarded.append(r)

    orderdict = Query(Cache_dict).get(WEPAYORDERID).get('content')       
    
    extreward = lambda x:getextreward(x, extrewardconfig)
    return render_template('agm1.0/pay/agm_seller_awards.html',
        rewarded=rewarded, reward_wait=reward_wait, total=total, seller=agmseller, pDT=printDateTime)        